package com.qianji.petmall.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.qianji.common.constant.AuthConstant;
import com.qianji.common.to.GiteeUserVo;
import com.qianji.common.to.MemberResponseVo;
import com.qianji.common.utils.HttpUtils;
import com.qianji.common.utils.R;
import com.qianji.petmall.authserver.constant.GiteeConstant;
import com.qianji.petmall.authserver.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author liang zai
 * @date 2022/3/30 12:07
 * @description
 */
@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2/gitee/success")
    public String OAuth2(@RequestParam("code")String code, HttpSession session) throws Exception {

        HashMap<String, String> map = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id",GiteeConstant.clientId);
        map.put("redirect_uri",GiteeConstant.callback);
        map.put("client_secret",GiteeConstant.clientSecret);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost(GiteeConstant.address, GiteeConstant.path, "post", new HashMap<>(), map, "");

        //2、处理
        if (response.getStatusLine().getStatusCode() == 200){
            //获取到了access_token
            String json = EntityUtils.toString(response.getEntity());// 获取到json串

            GiteeUserVo userVo = JSON.parseObject(json, GiteeUserVo.class);
            if (userVo!=null){
                log.info("gitee 授权登录返回 accessToken：{}", userVo.getAccessToken());
                R oauthLogin = memberFeignService.oauthLogin(userVo);
                if (oauthLogin.getCode()==0){
                    //登录失成功跳回首页
                    MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {});
                    log.info("登录成功,用户信息:{}",data.toString());
                    //第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookies
                    //以后浏览器访问就得带上这个cookies
                    //子域之间：petmall.com auth.petmall.com order.petmall.com
                    //发卡的时候指定域名为父域名
                    //TODO 作用域 默认是当前的作用域
                    //TODO 使用JSON的序列化方式储存到redis中
                    session.setAttribute(AuthConstant.LOGIN_USER,data);
                    return "redirect:http://petmall.com";
                }
            }

        }else {
            //登录失败跳回登录页
            return "redirect:http://auth.petmall.com/login.html";
        }

        //登录失败跳回登录页
        return "redirect:http://auth.petmall.com/login.html";
    }

}
